/**
 * 文件上传
 * Created by zhaijg.
 */
'use strict';
angular.module('app')
    .factory('fileUploadServices', ['$modal','$http','apiUrl', function ($modal,$http,apiUrl) {
        return {
            uploadFile: function (fileIsMultiple) {
                var modalInstance = $modal.open({
                    templateUrl: 'tpl/modal/fileUploadModal.html',
                    controller: 'uploadModalCtrl',
                    size: 'lg',
                    resolve: {
                        isMultiple: function () {
                            return fileIsMultiple;
                        }
                    }
                });
                //操作返回
                return modalInstance.result;
            },
            /**
             * 删除oss 文件列表
             * @param list
             * @returns {HttpPromise}
             */
            delFileList: function (list) {
                if(list.length==0){
                    return null;
                }else{
                    var dataList = [];
                    for(var i=0;i<list.length;i++){
                        if(list[i]!=""){
                            dataList.push(list[i]);
                        }
                    }
                    if(dataList.length>0){
                        return $http.delete(apiUrl+"/oss/batch/del",{"data":{list:dataList}});
                    }
                }
            }
        };
    }]);
/**
 * 文件上传控制器
 * Created by zhaijg.
 */
'use strict';
app.controller('uploadModalCtrl', ['$scope', '$modalInstance','isMultiple', 'Upload', "$http", 'apiUrl', '$timeout',
    function ($scope, $modalInstance,fileIsMultiple, Upload, $http, apiUrl, $timeout) {
        $scope.isMultiple = fileIsMultiple;
        var uploadData = [];
        //上传单个
        $scope.upload = function (index) {
            getOssData($scope.files[index])
        }
        //取消上传
        $scope.cancel = function (index) {
            $scope.files.splice(index, 1);
        }
        $scope.progress = 0;
        var upNum = 0;
        //上传所有
        $scope.uploadAll = function () {
            if ($scope.files && $scope.files.length) {
                for (var i = 0; i < $scope.files.length; i++) {
                    getOssData($scope.files[i]);
                }
            }
        }
        function getOssData(file) {
            var lastIndex = file.name.lastIndexOf(".");
            //var fileSuffix = file.name.split(".")[1];
            var fileSuffix = "jpg";
            if(lastIndex!=-1){
                fileSuffix = file.name.substr(lastIndex+1, file.name.length);
            }
            $http.get(apiUrl + "/oss/policy?bucket=ficc-temp&pre-key=week/del&suffix=" + fileSuffix).success(function (data) {
                Upload.upload({
                    url: data.result.location,
                    fields: {OSSAccessKeyId: data.result.OSSAccessKeyId, Signature: data.result.Signature, policy: data.result.policy, key: data.result.key},
                    file: file
                }).progress(function (evt) {
                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                    file["progress"] = progressPercentage;
                    //console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
                }).success(function (updata, status, headers, config) {
                    if( !$scope.isMultiple){
                        uploadData = [];
                    }
                    uploadData.push(data.result.location + data.result.key);
                    file["isSuccess"] = true;
                    //console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
                    $timeout(function () {
                        upNum = upNum + 1;
                        $scope.progress = parseInt(100.0 * upNum / ($scope.files != undefined ? $scope.files.length : 0));
                    })
                }).error(function (updata, status, headers, config) {
                    file["isError"] = true;
                    //console.log('error status: ' + status);
                })
            });
        }

        //点确认按钮关闭
        $scope.ok = function () {
            $modalInstance.close(uploadData);
        };
        //取消按钮
        $scope.cancelModal = function () {
            $modalInstance.dismiss('cancel');
        };

    }]);